package com.crm.crm.controller;

import com.crm.crm.annotation.Log;
import com.crm.crm.domain.BusinessOpportunity;
import com.crm.crm.domain.ChannelCount;
import com.crm.crm.domain.ClueProcess;
import com.crm.crm.domain.dto.PageQueryParams;
import com.crm.crm.domain.dto.business.BusinessListDto;
import com.crm.crm.domain.dto.report.CountShipDto;
import com.crm.crm.domain.vo.*;
import com.crm.crm.domain.vo.business.BusinessVo;
import com.crm.crm.domain.vo.contract.ContractReportResponse;
import com.crm.crm.domain.vo.business.result.Result;
import com.crm.crm.service.ClueProcessService;
import com.crm.crm.service.ClueService;
import com.crm.crm.service.ReportService;
import lombok.Data;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.crm.domain.Contract;
import com.crm.crm.domain.dto.report.ContractStatisticsListDto;
import com.crm.crm.domain.vo.contract.ContractListVo;
import com.crm.crm.service.ContractService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/report")
public class ReportController {
    @Autowired
    private ReportService reportService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private ClueService clueService;
    @Autowired
    private ClueProcessService clueProcessService;

    @Log("线索转化漏斗")
    @GetMapping("/getVulnerabilityMap/{startDate}/{endDate}")
    public Result<ReportFunnelVo> getVulnerabilityMap(@PathVariable LocalDate startDate, @PathVariable LocalDate endDate) {
        log.info("线索转化漏斗，时间范围：{} 至 {}", startDate, endDate);
        ReportFunnelVo indexBasicDataVo = reportService.getVulnerabilityMap(startDate, endDate);
        return Result.success(indexBasicDataVo);
    }


    //====这里面放线索统计的相关代码=====================================

    /*线索统计的分页查询*/
    @GetMapping("/cluesStatisticsList")
    public Result list(CountShipDto dto) {
        log.info("分页查询参数：{}", dto);
        // 创建分页对象（pageNum 是当前页码，pageSize 是每页记录数）
        Page<ClueProcess> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        // 调用 service 分页查询方法
        Page<ClueProcess> resultPage = clueProcessService.list(dto, page);
        log.info("分页查询结果：{}", resultPage);
        // 将 Page<ClueProcess> 转换为 List<ClueProcessVo>
        List<ClueProcessVo> voList = resultPage.getRecords().stream()
                .map(clueProcess -> {
                    ClueProcessVo vo = new ClueProcessVo();
                    BeanUtils.copyProperties(clueProcess, vo);
                    return vo;
                })
                .toList();

// 构造最终结果：将 total 和 rows 提升到顶层
        Result result = Result.success();
        result.put("total", resultPage.getTotal());
        result.put("rows", voList);
        return result;

    }

    //线索统计的曲线图   /api/report/cluesStatistics/2025-05-30/2025-06-06
    //统计新增线索和线索总数
    @GetMapping("/cluesStatistics/{beginCreateTime}/{endCreateTime}")
    public ContractReportResponse cluesStatistics(@PathVariable("beginCreateTime") String beginCreateTime,
                                                  @PathVariable("endCreateTime") String endCreateTime) {
        log.info("接收到统计请求，时间范围：{} - {}", beginCreateTime, endCreateTime);
        ContractReportResponse response = clueService.cluesStatistics(beginCreateTime, endCreateTime);
        return response;
    }

    //====这里面放客户的相关代码========================================
    //    分页查询
    @GetMapping("/contractStatisticsList")
    public Result list(ContractStatisticsListDto dto,
                       @RequestParam Map<String, String> params) {
        dto.setBeginCreateTime(params.get("beginCreateTime"));
        dto.setEndCreateTime(params.get("endCreateTime"));
        log.info("分页查询参数：{}", dto);
        // 创建分页对象（pageNum 是当前页码，pageSize 是每页记录数）
        Page<Contract> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        // 调用 service 分页查询方法
        Page<Contract> resultPage = contractService.list(dto, page);
        log.info("分页查询结果：{}", resultPage);
        // 将 Page<ContractStatisticsListDto> 转换为 List<ContractListVo>
        List<ContractListVo> voList = resultPage.getRecords().stream()
                .map(contract -> {
                    ContractListVo vo = new ContractListVo();
                    BeanUtils.copyProperties(contract, vo);
                    return vo;
                })
                .toList();

// 构造最终结果：将 total 和 rows 提升到顶层
        Result result = Result.success();
        result.put("total", resultPage.getTotal());
        result.put("rows", voList);
        return result;
    }

    //    统计当前时间段类新增客户和累计客户数
    @GetMapping("/contractStatistics/{beginCreateTime}/{endCreateTime}")
    public ContractReportResponse contractStatistics(@PathVariable("beginCreateTime") String beginCreateTime,
                                                     @PathVariable("endCreateTime") String endCreateTime) {
        log.info("接收到统计请求，时间范围：{} - {}", beginCreateTime, endCreateTime);
        ContractReportResponse response = contractService.contractStatistics(beginCreateTime, endCreateTime);
        return response;
    }


    //    统计客户选择的学科
    @GetMapping("/subjectStatistics/{beginCreateTime}/{endCreateTime}")
    public Result countProjects(@PathVariable String beginCreateTime,
                                @PathVariable String endCreateTime) {
        List<SubjectCountVo> subjectCountVos = contractService.countProject(beginCreateTime, endCreateTime);
        return Result.success(subjectCountVos);
    }

//==下面写来源渠道统计相关代码=========================================

    //统计来源的渠道数据
    @GetMapping("/chanelStatistics/{beginCreateTime}/{endCreateTime}")
    public Result CountChannel(@PathVariable String beginCreateTime,
                               @PathVariable String endCreateTime) {
        List<Map<Integer, String>> channelCount = contractService.CountChannel(beginCreateTime, endCreateTime);
        return Result.success(channelCount);
    }

    //统计活动数据
    @GetMapping("/activityStatistics/{beginCreateTime}/{endCreateTime}")
    public Result CountActivity(@PathVariable String beginCreateTime,
                                @PathVariable String endCreateTime) {
        List<Map<String, Integer>> activityCount = contractService.CountActivitystics(beginCreateTime, endCreateTime);
        return Result.success(activityCount);
    }

// todo 渠道统计的分页查询
//    时间来不及了，直接建表ChannelCount写的假数据，没关联其他表
    @GetMapping("/activityStatisticsList")
    public PageCountResult<ChannelCount> activityStatisticsList(
            @RequestParam(required = false) String beginCreateTime,
            @RequestParam(required = false) String endCreateTime,
            @RequestParam(required = false) String code,
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {

        return reportService.activityStatisticsList(beginCreateTime, endCreateTime, code, name, pageNum, pageSize);
}


//===下面写销售统计的相关代码=============================================
//    这个分页查询的前端界面是假分页，
//    所以这里就不对分页参数进行处理了

    //    统计所属人的分页查询  ownerShipStatisticsList
    @GetMapping("/ownerShipStatisticsList/{beginCreateTime}/{endCreateTime}")
    public PageCountResult<CountShipVo> countOwner(
            @PathVariable String beginCreateTime,
            @PathVariable String endCreateTime) {

        List<CountShipVo> result = contractService.countOwner(beginCreateTime, endCreateTime);

        return PageCountResult.of(result, result.size());
    }


    //    统计所属部门的分页查询
    @GetMapping("/deptStatisticsList/{beginCreateTime}/{endCreateTime}")
    public PageCountResult<CountShipVo> countDept(
            @PathVariable String beginCreateTime,
            @PathVariable String endCreateTime) {

        List<CountShipVo> result = contractService.countDept(beginCreateTime, endCreateTime);

        return PageCountResult.of(result, result.size());
    }

    //    统计所属渠道的分页查询
    @GetMapping("/channelStatisticsList/{beginCreateTime}/{endCreateTime}")
    public PageCountResult<CountShipVo> countChannel(
            @PathVariable String beginCreateTime,
            @PathVariable String endCreateTime) {

        List<CountShipVo> result = contractService.countChannel(beginCreateTime, endCreateTime);

        return PageCountResult.of(result, result.size());
    }

    //    销售统计的曲线图，统计了每天的销售金额
//    salesStatistics
    @GetMapping("/salesStatistics/{beginCreateTime}/{endCreateTime}")
    public ContractReportResponse salesStatistics(@PathVariable("beginCreateTime") String beginCreateTime,
                                                  @PathVariable("endCreateTime") String endCreateTime) {
        log.info("接收到统计请求，时间范围：{} - {}", beginCreateTime, endCreateTime);
        ContractReportResponse response = contractService.salesStatistics(beginCreateTime, endCreateTime);
        return response;
    }


//===================================================================


}
